<template>
  <view class="content">
    <!-- 顶部导航 -->
    <page-header title="已完成待办" :showBack="true"> </page-header>

    <!-- 主体内容 -->
    <view class="page-body">
      <!-- 标签选择栏 -->
      <tab-selector
        :tabs="tabs"
        v-model:activeTab="activeTabIndex"
        @change="handleTabChange"
      />

      <!-- 待办列表 -->
      <scroll-view
        class="todo-container"
        scroll-y="true"
        @scrolltolower="loadMore"
      >
        <completed-todo-list
          :todos="filteredTodos"
          @delete="deleteTodo"
          @toggle-complete="uncompleteTask"
        />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import pageHeader from "@/components/pageHeader.vue";
import CompletedTodoList from "@/components/CompletedTodoList.vue";
import TabSelector from "@/components/TabSelector.vue";
import { todoApi } from "@/api";

// 页面数据
const activeTabIndex = ref(0);

// 已完成待办数据
const completedTodoListData = ref([]);
const tabs = ref([]);
const allCompletedTodos = ref([]);

// 根据当前标签筛选待办
const filteredTodos = computed(() => {
  if (!completedTodoListData.value.length || activeTabIndex.value < 0) {
    return [];
  }

  const currentLabelData = completedTodoListData.value[activeTabIndex.value];
  if (!currentLabelData || !currentLabelData.todoItems) {
    return [];
  }

  // 转换数据格式以适配CompletedTodoList组件
  return currentLabelData.todoItems.map((item) => ({
    id: item.todoItemId,
    content: item.content,
    completed: true, // 已完成待办默认为true
    createdAt: item.createdAt,
    updatedAt: item.updatedAt,
    labelId: currentLabelData.labelId,
    labelName: currentLabelData.labelName,
  }));
});

// 获取已完成待办列表数据的方法
const loadCompletedTodoList = async () => {
  try {
    const res = await todoApi.getCompletedTodoList();
    if (res.success && res.data) {
      // 存储完整的数据
      completedTodoListData.value = res.data;

      // 生成标签数据
      tabs.value = res.data.map((item, index) => ({
        id: item.labelId,
        name: item.labelName,
        index: index,
      }));

      // 扁平化所有已完成待办数据
      allCompletedTodos.value = res.data.flatMap((label) =>
        label.todoItems.map((todo) => ({
          ...todo,
          id: todo.todoItemId, // 统一id字段名
          labelId: label.labelId,
          labelName: label.labelName,
          completed: true,
        }))
      );
    }
  } catch (error) {
    console.error("获取已完成待办列表失败:", error);
  }
};

// 标签切换处理
const handleTabChange = (tab, index) => {
  console.log("Tab changed:", tab.name, index);
};

// 页面方法
const deleteTodo = (id) => {
  uni.showModal({
    title: "删除待办",
    content: "确定要删除这个待办事项吗？",
    success: async function (res) {
      if (res.confirm) {
        try {
          // 调用删除API
          const response = await todoApi.deleteTodo({ id: id });

          if (response.success) {
            // 在当前标签的todoItems中查找待办
            const currentLabelData =
              completedTodoListData.value[activeTabIndex.value];
            if (!currentLabelData || !currentLabelData.todoItems) {
              return;
            }

            const todoIndex = currentLabelData.todoItems.findIndex(
              (item) => item.todoItemId === id
            );
            if (todoIndex !== -1) {
              // 从列表中移除
              currentLabelData.todoItems.splice(todoIndex, 1);
            }

            // 发送全局事件，同步删除首页中的数据
            uni.$emit("deleteTodo", id);

            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: response.msg || "删除失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("删除已完成待办失败:", error);
          uni.showToast({
            title: "删除失败，请重试",
            icon: "none",
          });
        }
      }
    },
  });
};

// 取消完成状态
const uncompleteTask = async (id) => {
  try {
    // 在当前标签的todoItems中查找待办
    const currentLabelData = completedTodoListData.value[activeTabIndex.value];
    if (!currentLabelData || !currentLabelData.todoItems) {
      return;
    }

    const todoIndex = currentLabelData.todoItems.findIndex(
      (item) => item.todoItemId === id
    );
    if (todoIndex === -1) {
      uni.showToast({
        title: "待办不存在",
        icon: "none",
      });
      return;
    }

    const todoItem = currentLabelData.todoItems[todoIndex];

    // 调用更新API，将待办设置为未完成
    const response = await todoApi.updateTodo({
      id: id,
      isCompleted: false,
      content: todoItem.content, // 传入原内容
      labels: [currentLabelData.labelId], // 传入当前标签ID
    });

    if (response.success) {
      // 从已完成列表中移除
      currentLabelData.todoItems.splice(todoIndex, 1);

      // 发送全局事件，通知首页和其他页面刷新数据
      uni.$emit("refreshTodoList");
      uni.$emit("todoUncompleted", {
        ...todoItem,
        id: todoItem.todoItemId,
        completed: false,
      });

      uni.showToast({
        title: "已恢复到未完成状态",
        icon: "none",
      });
    } else {
      uni.showToast({
        title: response.msg || "操作失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("取消完成状态失败:", error);
    uni.showToast({
      title: "操作失败，请重试",
      icon: "none",
    });
  }
};

const loadMore = () => {
  console.log("加载更多已完成待办...");
};

// 页面加载
onMounted(async () => {
  console.log("已完成待办页面已加载");

  // 获取已完成待办列表数据
  await loadCompletedTodoList();

  // 监听完成状态变化事件
  uni.$on("completedTodoStatusChanged", () => {
    // 重新获取已完成待办数据
    loadCompletedTodoList();
  });

  // 监听待办列表刷新事件
  uni.$on("refreshCompletedTodoList", () => {
    loadCompletedTodoList();
  });
});

// 页面卸载时清理事件监听
onUnmounted(() => {
  uni.$off("completedTodoStatusChanged");
  uni.$off("refreshCompletedTodoList");
});
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  width: 100%;
  overflow-x: hidden;
}

.page-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  position: relative;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  padding-top: 80rpx; /* 为固定的tab-selector留出空间 */
}

.todo-container {
  flex: 1;
  padding: 0 20rpx;
  padding-bottom: 100rpx;
  box-sizing: border-box;
  width: 100%;
}

.empty-list {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80rpx;
  color: #cccccc;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 添加固定tab-selector的样式 */
:deep(.tab-selector) {
  position: fixed;
  top: calc(var(--status-bar-height) + 90rpx); /* 根据page-header的高度调整 */
  left: 0;
  right: 0;
  z-index: 100;
}
</style>
